package com.uchiha.nova.mainService.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.uchiha.nova.core.annotation.ApiLog;
import com.uchiha.nova.core.model.dto.WechaterUserRegisterDTO;
import com.uchiha.nova.core.tool.constant.HeaderConstant;
import com.uchiha.nova.core.tool.constant.RedisCacheConstants;
import com.uchiha.nova.core.feign.AuthFeignService;
import com.uchiha.nova.core.model.dto.NovaOauthTokenDTO;
import com.uchiha.nova.core.model.dto.PasswordModifyDTO;
import com.uchiha.nova.core.model.dto.RefreshTokenDTO;
import com.uchiha.nova.core.model.entity.OauthClientDetails;
import com.uchiha.nova.core.tool.api.R;
import com.uchiha.nova.core.tool.support.AuthToken;
import com.uchiha.nova.core.tool.support.BaseController;
import com.uchiha.nova.core.tool.support.NovaUser;
import com.uchiha.nova.core.tool.util.AuthUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author 周林静
 * @Date 2025-03-28 16:00
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "账户相关")
public class UserController extends BaseController {
    @Resource
    AuthFeignService authFeignService;
    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @GetMapping(value = "/info")
    @Operation(description = "获取前端信息")
    public R info() {
        NovaUser novaUser = getNovaUser();
        log.info("info:{}", novaUser.getUserId());
        return authFeignService.getWebUserInfoVO(novaUser.getUserId());
    }

    @GetMapping("/wechat/info")
    @Operation(description = "获取小程序登陆之后的个人信息")
    public R wechatInfo() {
        NovaUser novaUser = getNovaUser();
        log.info("info:{}", novaUser.getUserId());
        return authFeignService.getWeChaterInfo(novaUser.getUserId());
    }

    @GetMapping("/logout")
    public R logout(HttpServletRequest request) {
        String token = request.getHeader(HeaderConstant.NOVA_AUTH).replace("Bearer ", "");
        log.info("logout:{}", token);
        redisTemplate.delete(RedisCacheConstants.NOVA_OAUTH_TOKEN + token);
        return R.status(true);
    }

    @GetMapping("refreshToken")
    public R refreshToken(@RequestParam String refreshToken,HttpServletRequest request) {
        String token = request.getHeader(HeaderConstant.NOVA_AUTH).replace("Bearer ", "");
        log.info("refreshToken:{}", token);
        RefreshTokenDTO refreshTokenDTO = new RefreshTokenDTO();
        refreshTokenDTO.setRefreshToken(refreshToken);
        refreshTokenDTO.setToken(token);
        refreshTokenDTO.setClientId(request.getHeader(HeaderConstant.NOVA_CLIENT));
        return authFeignService.refreshToken(refreshTokenDTO);
    }

    @PostMapping("/login")
    @Operation(description = "默认登录")
    @ApiLog
    public R login(@RequestBody NovaOauthTokenDTO dto, HttpServletRequest request, HttpServletResponse response) {
        log.info("login:{}", dto);
        if (null == dto.getPassword() || "".equals(dto.getPassword())) {
            return R.fail("请填写密码");
        }

        if (null == dto.getUsername() || "".equals(dto.getUsername())) {
            return R.fail("请填写账户");
        }
        String clientId = request.getHeader(HeaderConstant.NOVA_CLIENT);
        String clientSecrt = request.getHeader(HeaderConstant.NOVA_CLIENT_SECRT);
        if (null == clientId || "".equals(clientId)) {
            return R.fail("错误的clientId");
        }

        if (null == clientSecrt || "".equals(clientSecrt)) {
            return R.fail("错误的clientSecrt");
        }
        dto.setClientId(clientId);
        dto.setClientSecret(clientSecrt);
        R r = authFeignService.getAccessToken(dto);
        if (r.isSuccess()) {
            AuthToken authToken = JSONObject.parseObject(JSONObject.toJSONString(r.getData()), AuthToken.class);
            OauthClientDetails clientDetails = (OauthClientDetails) redisTemplate.opsForValue().get(RedisCacheConstants.NOVA_OAUTH_CLIENT + dto.getClientId());
            redisTemplate.opsForValue().set(RedisCacheConstants.NOVA_OAUTH_TOKEN + authToken.getAccessToken(), authToken.getAccessToken(), clientDetails.getAccessTokenValidity(), TimeUnit.SECONDS);

        }
        return r;
    }

    @GetMapping("/getNav")
    @ApiLog(value = "获取侧边栏")
    @Operation(description = "获取侧边栏导航")
    public R getNav() {
        NovaUser novaUser = getNovaUser();
        return authFeignService.getNav(novaUser.getUserId());
    }

    @PostMapping("/passwordModify")
    @Operation(description = "修改密码")
    public R passwordModify(@RequestBody PasswordModifyDTO dto) {
        NovaUser novaUser = getNovaUser();
        dto.setUserId(novaUser.getUserId());
        return authFeignService.passwordModify(dto);
    }

    @PostMapping("/wechat/login")
    public R wechatLogin(@RequestBody NovaOauthTokenDTO dto,HttpServletRequest request){

        String clientId = request.getHeader(HeaderConstant.NOVA_CLIENT);
        String clientSecrt = request.getHeader(HeaderConstant.NOVA_CLIENT_SECRT);
        if (null == clientId || "".equals(clientId)) {
            return R.fail("错误的clientId");
        }

        if (null == clientSecrt || "".equals(clientSecrt)) {
            return R.fail("错误的clientSecrt");
        }
        dto.setClientId(clientId);
        dto.setClientSecret(clientSecrt);
        dto.setGrantType("wx_code");
        R r = authFeignService.getAccessToken(dto);
        if (r.isSuccess()) {
            AuthToken authToken = JSONObject.parseObject(JSONObject.toJSONString(r.getData()), AuthToken.class);
            OauthClientDetails clientDetails = (OauthClientDetails) redisTemplate.opsForValue().get(RedisCacheConstants.NOVA_OAUTH_CLIENT + dto.getClientId());
            redisTemplate.opsForValue().set(RedisCacheConstants.NOVA_OAUTH_TOKEN + authToken.getAccessToken(), authToken.getAccessToken(), clientDetails.getAccessTokenValidity(), TimeUnit.SECONDS);

        }
        return r;
    }

    @PostMapping("/wechat/register")
    public R wechatRegister(@RequestBody WechaterUserRegisterDTO dto){

        return authFeignService.wechatRegister(dto);
    }
}
